package com.yao;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class IntegerFilter extends DocumentFilter {
    
    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
        if (text == null) {
            super.insertString(fb, offset, "", attr);
        } else {
            StringBuilder sbuiler = new StringBuilder();
            for (int i = 0; i < text.length(); i++) {
                int code = text.codePointAt(0);
                if (code >= 48 && code <= 57) {
                    sbuiler.append(text.charAt(i));
                }
            }
            super.insertString(fb, offset, sbuiler.toString(), attr);
        }
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        if (text == null) {
            super.replace(fb, offset, 0, "", attrs);
        } else {
            StringBuilder sbuiler = new StringBuilder();
            int len = 0;
            for (int i = 0; i < text.length(); i++) {
                int code = text.codePointAt(0);
                if (code >= 48 && code <= 57) {
                    sbuiler.append(text.charAt(i));
                } else {
                    len++;
                }
            }
            super.replace(fb, offset, len, sbuiler.toString(), attrs);
        }
    }

}
